<script setup lang="ts">
import {computed, defineExpose, defineOptions, ref, watch} from 'vue';
import {fetchGetOrder, fetchGetOrderPage} from "@/service/api/order";
import {SelectOption} from "naive-ui";
import {fetchGetTemplate} from "@/service/api/template";
import {useLoading} from "~/packages/hooks";
import {EBuilder} from "@/components/formdesigner";
import {fetchGetDeployPage} from "@/service/api";
import {fetchStartTask} from "@/service/api/current-task";

const {startLoading, endLoading} = useLoading();

defineOptions({
  name: 'AppXj'
});

const ebForm = ref();
const showModal = ref(false);
const options = ref<SelectOption[]>([]);
const step = ref(1);
const title = computed(() => {
  if (step.value === 1) {
    return '发起询价-选择订单'
  } else if (step.value === 2) {
    return '发起询价-填写询价信息'
  }
  return ''
})
const orderData = ref<Api.Entity.Order | {}>({});
const selectedOrderCode = ref('');
const formField = ref<any>({});
const formData = ref<any>({
  processDefinitionId: '',
  orderId: 0,
  formData: {}
});
const templateData = ref<any>({});

//保存按钮
const submitCallback = () => {
  ebForm.value.getData().then((data: any) => {
    formData.value.formData = data
    fetchStartTask(formData.value).then((res) => {
      if (res.error) {
        window.$message?.error(res.error.message)
      } else {
        window.$message?.success('操作成功');
        showModal.value = false
      }
    })
    // console.log("submitCallback:",data)`
  })
};

//取消按钮
const cancelCallback = () => {
  showModal.value = false;
};
//打开或关闭弹框
const toggleModal = () => {
  showModal.value = !showModal.value;
}
//下一步
const nextStep = () => {
  startLoading();
  if (selectedOrderCode.value === '') {
    window.$message?.error('请选择订单')
    return
  }
  getOrderByCode();
  endLoading();
}
//获取订单
const getOrderByCode = async () => {
  let {error, data} = await fetchGetOrder({
    filters: [
      {
        property: 'orderNo',
        operator: 'eq',
        value: selectedOrderCode.value
      }
    ]
  })
  if (!error && data) {
    orderData.value = data
    if (data.templateId) {
      await getTemplateData(data.templateId)
    }
  }
}


//获取表单
const getTemplateData = async (templateId: number) => {
  let {error, data} = await fetchGetTemplate(templateId);
  templateData.value = data;
  if (!error && data) {
    if (data.formData) {
      formField.value = data.formData;
      step.value = 2;
      await getDeploy();
    }
  }
}
const getDeploy = async () => {
  const res = await fetchGetDeployPage({
    pageNumber: 1,
    pageSize: 1,
    params: {
      key: templateData.value.flowData.model_code,
      name: templateData.value.flowData.model_name
    }
  });
  formData.value.processDefinitionId = res.data?.content[0].id
}
//获取订单列表
const getOptionsData = async () => {
  let {error, data} = await fetchGetOrderPage({
    pageNumber: 1,
    pageSize: 100,
    searchProperty: null,
    searchValue: null,
    orderProperty: null,
    orderDirection: null,
    filters: [],
    params: {}
  });
  if (!error) {
    if (data) {
      options.value = [];
      data?.content.forEach((item: Api.Entity.Order) => {
        options.value.push({
          label: item.orderNo,
          value: item.orderNo
        })
      })
    }

  }
}
const init = () => {
  step.value = 1
  orderData.value = {}
  selectedOrderCode.value = ''
}
getOptionsData();
defineExpose(
  {
    toggleModal
  }
)
watch(showModal, (val) => {
  if (!val) {
    init();
  }
})
</script>

<template>
  <n-modal
    v-model:show="showModal"
    preset="dialog"
    :show-icon="false"
    positive-text="确认"
    negative-text="取消"
    @positive-click="submitCallback"
    @negative-click="cancelCallback"
  >
    <template #icon>

    </template>
    <template #header>
      {{ title }}
    </template>
    <template #default>
      <n-space vertical v-if="step === 1">
        <n-select
          v-model:value="selectedOrderCode"
          filterable
          placeholder="选择歌曲"
          :options="options"
          @update:value="(v) => { selectedOrderCode = v; }"
        />
      </n-space>
      <EBuilder ref="ebForm" :pageSchema="formField" v-if="step === 2"/>
    </template>
    <template #action>
      <n-space>
        <n-button type="default" @click="cancelCallback">
          取消
        </n-button>
        <n-button type="primary" @click="nextStep" v-if="step === 1">
          下一步
        </n-button>
        <n-button type="primary" @click="submitCallback" v-if="step === 2">
          发起询价
        </n-button>
      </n-space>
    </template>
  </n-modal>
</template>

<style scoped>

</style>
